package com.epfresh.supplier.activity;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.epfresh.api.dialog.AreaDialog;
import com.epfresh.api.dialog.MarketDialog;
import com.epfresh.api.entity.FileUploadResponse;
import com.epfresh.api.entity.RequestEntityMapSupply;
import com.epfresh.api.entity.RequestEntitySupply;
import com.epfresh.api.entity.RequestTag;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.entity.StatusEntity;
import com.epfresh.api.global.BaseActivity;
import com.epfresh.api.global.BaseApplication;
import com.epfresh.api.global.DataManager;
import com.epfresh.api.global.MessageCentre;
import com.epfresh.api.http.HttpRequest;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.ucrop.PhotoCore;
import com.epfresh.api.universalimageloader.core.ImageLoader;
import com.epfresh.api.universalimageloader.core.assist.ImageSize;
import com.epfresh.api.universalimageloader.core.imageaware.ImageViewAware;
import com.epfresh.api.utils.CustomDialog;
import com.epfresh.api.utils.FileUtil;
import com.epfresh.api.utils.JsonUtils;
import com.epfresh.api.utils.L;
import com.epfresh.api.utils.LocalDisplay;
import com.epfresh.api.utils.VerificationUtils;
import com.epfresh.api.widget.CommonInputItem;
import com.epfresh.api.widget.PhotoUploadView;
import com.epfresh.api.widget.gradient.inter.GradientStyle;
import com.epfresh.api.widget.gradient.utils.GradientUtils;
import com.epfresh.api.widget.gradient.utils.LinearGradientUtil;
import com.epfresh.api.widget.gradient.view.GradientActionBar;
import com.epfresh.api.widget.gradient.view.GradientScrollView;
import com.epfresh.supplier.R;
import com.epfresh.supplier.constant.Constant;
import com.epfresh.supplier.entity.Category;
import com.epfresh.supplier.entity.CertInfo;
import com.epfresh.supplier.entity.City;
import com.epfresh.supplier.entity.CityAddressList;
import com.epfresh.supplier.entity.ContentEntity;
import com.epfresh.supplier.entity.Images;
import com.epfresh.supplier.entity.Market;
import com.epfresh.supplier.entity.PickUpAddressesEntity;
import com.epfresh.supplier.entity.Store;
import com.epfresh.supplier.entity.StoreBaseInfo;
import com.epfresh.supplier.entity.StoreInfo;
import com.epfresh.supplier.view.tag.FlowLayout;
import com.epfresh.supplier.view.tag.TagAdapter;
import com.epfresh.supplier.view.tag.TagFlowLayout;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.tencent.mmkv.MMKV;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Created by wzh on 2016/5/6.
 */
public class StoreActivity extends BaseActivity implements PhotoCore.PhotoResult {
    private CommonInputItem vStoreName;
    private CommonInputItem vStoreCategory;
    private CommonInputItem vMarket;
    private CommonInputItem vMarketId;
    private CommonInputItem vCity;
    private CommonInputItem vMarketArea;
    private CommonInputItem vDescription;
    private TagFlowLayout categoryTag;
    private TagAdapter<Category> adapter;
    private List<Category> listCategory = new ArrayList<>();
    private View rlOrder;
    private View rlRefuse;
    private TextView tvRefuse;
    private TextView tvBtn;
    private TextView tvCacheSave;
    private View vStoreEnsure;
    private PhotoUploadView vStoreAvater;
    private int TYPE;
    private PhotoCore photoCore;
    private String filePath = FileUtil.getImgCacheDir() + "/" + "store_avatar";
    private boolean isFirst = true;
    private StoreBaseInfo currentStoreInfo = new StoreBaseInfo();
    private String currentLogoPath = "";
    private int w;
    private GradientActionBar vToolbar;
    private View vLine;
    private int top = -1;
    private LinearGradientUtil linearGradientUtil;
    private String merchantId;
    //public static boolean isMain;//后面审核中也需要判断
    private boolean isStore;
    private LinearLayout llProgress;
    private int toIndex;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_store);
        isStore = MMKV.defaultMMKV().decodeBool("isStore");
        toIndex = MMKV.defaultMMKV().decodeInt("toIndex", -1);
        MMKV.defaultMMKV().encode("isStore", false);
        vToolbar = (GradientActionBar) findViewById(R.id.ll_toolbar);
        toolbarTitle = (TextView) findViewById(R.id.toolbar_title);
        rightbtn = (TextView) findViewById(R.id.rightbtn);
        ivBack = (ImageView) findViewById(R.id.baseback);
        tvBack = (TextView) findViewById(R.id.tv_back_title);
        vLine = findViewById(R.id.v_line);
        vToolbar.setBackgroundColor(0x00ffffff);
        toolbarTitle.setText("申请开店");
        rightbtn.setText(getString(R.string.help));
//        rightbtn.setTextColor(0xff898989);
        //   rightbtn.setTextColor(0xffffffff);
        rightbtn.setVisibility(View.VISIBLE);
        rightbtn.setOnClickListener(this);
        filePath += "_" + getUser().getAccountId();
        if (savedInstanceState != null) {
            getIntent().putExtra(Constant.KEY_STORE_TYPE_STATUS, savedInstanceState.getInt(Constant.KEY_STORE_TYPE_STATUS));
        }
        initView();
        initPhotoCore();
        if (toIndex!=2) {
            tvBack.setVisibility(View.VISIBLE);
            tvBack.setText("退出登录");
            ivBack.setVisibility(View.GONE);
        } else {
            tvBack.setVisibility(View.GONE);
            ivBack.setVisibility(View.VISIBLE);
        }
        tvBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                intoLogin();
            }
        });
    }

    @Override
    protected View getToolBar() {
        return null;
    }

    private void intoLogin() {
        MMKV.defaultMMKV().encode("token", "");
        MMKV.defaultMMKV().encode("toIndex", -1);
        MessageCentre.getInstance().logoutAlias();
        SharedPreferences user = mContext.getSharedPreferences(
                "userinfo", Activity.MODE_PRIVATE);
        SharedPreferences.Editor editor = user.edit();
        editor.putString("password", "");
        editor.putString("accountId", "");
        editor.putString("access_token", "");
        editor.commit();
        clearUser();
        clearStoreInfo();
        BaseApplication.getInstance().putMerchant(null);
        Intent main = new Intent(this, LoginActivity.class);
        main.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(main);
        finish();
    }

    private void initPhotoCore() {
        photoCore = new PhotoCore(this, this);
        photoCore.setResultHeight(240);
        photoCore.setResultWidth(720);
        photoCore.setRatio(720, 240);
    }


    View.OnClickListener onCanNotEdit = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (TYPE == Constant.TYPE_STORE_STATUS_PRVIEW) {
                toast("店铺审核中不可修改");
            } else {
                toast("您仅可修改门头照与店铺简介，如需修改其他，请联系客服：400-0588-198");
            }
        }
    };

    private void initView() {
        llProgress = findViewById(R.id.ll_progress);
        vStoreName = (CommonInputItem) findViewById(R.id.ci_store_name);
        vStoreCategory = (CommonInputItem) findViewById(R.id.ci_store_category);
        vCity = (CommonInputItem) findViewById(R.id.ci_city);
        vMarket = (CommonInputItem) findViewById(R.id.ci_market_address);
        vMarketArea = (CommonInputItem) findViewById(R.id.ci_market_area);
        vMarketId = (CommonInputItem) findViewById(R.id.ci_market_id);
        vDescription = (CommonInputItem) findViewById(R.id.ci_description);
        vStoreCategory.setOnClickListener(this);
        vMarketArea.setOnClickListener(this);
        vStoreName.setOnCanNotEdit(onCanNotEdit);
        vStoreCategory.setOnCanNotEdit(onCanNotEdit);
        vCity.setOnCanNotEdit(onCanNotEdit);
        vMarket.setOnCanNotEdit(onCanNotEdit);
        vMarketArea.setOnCanNotEdit(onCanNotEdit);
        vMarketId.setOnCanNotEdit(onCanNotEdit);
        w = LocalDisplay.SCREEN_WIDTH_PIXELS - LocalDisplay.dp2px(50);
        w /= 4;
        categoryTag = (TagFlowLayout) findViewById(R.id.tag_category);

        adapter = new TagAdapter<Category>(listCategory) {
            @Override
            public View getView(FlowLayout parent, int position, Category category) {
                TextView tv = (TextView) LayoutInflater.from(StoreActivity.this).inflate(R.layout.category_market_tag,
                        parent, false);

                ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) tv.getLayoutParams();
                lp.width = w;
                tv.setLayoutParams(lp);
                tv.setText(category.getName());
                return tv;
            }
        };

        categoryTag.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {

                if (position < listCategory.size()) {
                    Category c = listCategory.get(position);
                    if ("-1".equals(c.getId())) {
                        String id = currentStoreInfo.getMainBusinessCategoryIds();
                        if ("-1".equals(id)) {
                            adapter.setSelectedList(new HashSet<Integer>());
                            vStoreCategory.setContentText("");
                            currentStoreInfo.setMainBusinessCategoryIds(null);
                            currentStoreInfo.setMainBusinessCategoryNames(null);
                        } else {
                            adapter.setSelectedList(position);
                            vStoreCategory.setContentText(c.getName());
                            currentStoreInfo.setMainBusinessCategoryIds(c.getId());
                            currentStoreInfo.setMainBusinessCategoryNames(c.getName());
                        }
                    } else {
                        Set<Integer> selectPosSet = categoryTag.getSelectedList();
                        StringBuilder sb = new StringBuilder();
                        StringBuilder sb2 = new StringBuilder();
                        ArrayList<Integer> list = new ArrayList<Integer>();
                        Set<Integer> set = new HashSet<Integer>();
                        if (selectPosSet != null && selectPosSet.size() > 0) {
                            for (Integer i : selectPosSet) {

                                Category category = listCategory.get(i);
                                if (!"-1".equals(category.getId())) {
                                    list.add(i);
                                    set.add(i);
                                }
                            }

                            if (list.size() > 0) {
                                Collections.sort(list, new Comparator<Integer>() {
                                    @Override
                                    public int compare(Integer o1, Integer o2) {
                                        return o1 - o2;
                                    }
                                });
                                for (int i = 0; i < list.size(); i++) {

                                    Category category = listCategory.get(list.get(i));
                                    sb.append(category.getName());
                                    sb.append(",");
                                    sb2.append(category.getId());
                                    sb2.append(",");
                                }
                            }

                            if (sb.toString().length() > 0 && sb.toString().lastIndexOf(",") == sb.toString().length() - 1) {
                                sb.delete(sb.toString().length() - 1, sb.toString().length());
                            }
                            if (sb2.toString().length() > 0 && sb2.toString().lastIndexOf(",") == sb2.toString().length() - 1) {
                                sb2.delete(sb2.toString().length() - 1, sb2.toString().length());
                            }


                            adapter.setSelectedList(set);
                            vStoreCategory.setContentText(sb.toString());
                            currentStoreInfo.setMainBusinessCategoryIds(sb2.toString());
                            currentStoreInfo.setMainBusinessCategoryNames(sb.toString());
                        } else {
                            vStoreCategory.setContentText("");
                            currentStoreInfo.setMainBusinessCategoryIds(null);
                            currentStoreInfo.setMainBusinessCategoryNames(null);
                        }
                    }
                }

                return true;
            }
        });
        categoryTag.setAdapter(adapter);
        rlRefuse = findViewById(R.id.rl_refuse_reason);
        tvRefuse = (TextView) findViewById(R.id.tv_refuse_content);
        vStoreAvater = (PhotoUploadView) findViewById(R.id.rl_store_avater);
        tvBtn = (TextView) findViewById(R.id.tv_btn);
        tvCacheSave = (TextView) findViewById(R.id.tv_save_cache);
        tvCacheSave.setOnClickListener(this);
        vStoreEnsure = findViewById(R.id.iv_store_ensuring);
        vStoreAvater.setOnClickListener(this);
        tvBtn.setOnClickListener(this);
        vMarket.setOnClickListener(this);
        vCity.setOnClickListener(this);
        TYPE = getIntent().getIntExtra(Constant.KEY_STORE_TYPE_STATUS, Constant.TYPE_STORE_STATUS_FIRST_OPEN);
        //TYPE = Constant.TYPE_STORE_STATUS_FIRST_OPEN;
        //第一次开店
        if (TYPE == Constant.TYPE_STORE_STATUS_FIRST_OPEN) {
            isFirst = true;
            first();
//            cmdStoreInfo = "store/info";
            requestUnPostStoreInfo();
        } else if (TYPE == Constant.TYPE_STORE_STATUS_EDIT) {//再次编辑
            isFirst = false;
            //  edit();
            first();
//            requestStoreInfo();
            requestUnPostStoreInfo();
        } else if (TYPE == Constant.TYPE_STORE_STATUS_PRVIEW) {//预览
            isFirst = false;
            preview();
            requestUnPostStoreInfo();
        } else if (TYPE == Constant.TYPE_STORE_STATUS_PRVIEW_EDIT) {//预览,可编辑
            isFirst = false;
            previewEdit(true);
            requestUnPostStoreInfo();
        } else {//错误

            finish();
        }

        linearGradientUtil = new LinearGradientUtil(0xffffffff, 0xff898989);

        if (isStore) {
            toolbarTitle.setText("店铺信息");
            llProgress.setVisibility(View.GONE);
        }
    }


    public void preview() {
        vStoreAvater.setClickable(false);
        tvBtn.setText(R.string.store_edit_btn);
        tvBtn.setVisibility(View.GONE);
        vStoreName.setEditable(false);
        vStoreCategory.setEditable(false);
        vMarket.setEditable(false);
        vMarketArea.setEditable(false);
        vMarketId.setEditable(false);
        vCity.setEditable(false);
        vDescription.setEditable(false);
        vMarket.setEditable(false);
        tvCacheSave.setVisibility(View.GONE);
//        rlTag.setVisibility(View.GONE);
//        vOrder.setVisibility(View.GONE);
        vStoreEnsure.setVisibility(View.VISIBLE);
    }

    public void previewEdit(boolean isPre) {
        vStoreAvater.setClickable(true);
        tvBtn.setText("提交");
        vStoreName.setEditable(false);
        vStoreCategory.setEditable(false);
        vMarket.setEditable(false);
        vMarketArea.setEditable(false);
        vCity.setEditable(false);
        vMarket.setEditable(false);
        if (!isPre && currentStoreInfo != null) {
            String mcn = currentStoreInfo.getMainBusinessCategoryNames();
            if (mcn == null || "".equals(mcn)) {
                vStoreCategory.setEditable(true);
            } else {
                vStoreCategory.setEditable(false);
//                vStoreName.setOnClickListener(this);
            }
            String stall = currentStoreInfo.getStall();

            if (stall == null || "".equals(stall)) {
//                vMarketId.setEditable(true);
            } else {
                vMarketId.setEditable(false);
//                vMarketId.setOnClickListener(this);
            }
            String areaName = currentStoreInfo.getAreaName();
            if (areaName == null || "".equals(areaName)) {
                vMarketArea.setEditable(true);
            } else {
                vMarketArea.setEditable(false);
            }
        }
        tvCacheSave.setVisibility(View.GONE);
    }

    public void first() {
        vStoreAvater.setClickable(true);
        tvBtn.setText("下一步");
    }

    public void edit() {
        vStoreAvater.setClickable(true);
        vMarket.setTextEnabled(true);
        tvBtn.setText("重新提交");
        tvBtn.setVisibility(View.VISIBLE);
        tvCacheSave.setVisibility(View.GONE);
    }

    public void updateStoreInfo() {
        if (currentStoreInfo != null && currentStoreInfo.isLegal()) {
            StoreInfo storeInfo = getStoreInfo();
            Store store = storeInfo.getStore();
            String logoUrl = currentStoreInfo.getHeaderImageUrl();
            if (store != null) {
                store.setName(currentStoreInfo.getName());
                store.setHeaderImageUrl(logoUrl);
                updateStoreInfo(getStoreInfo());
            }
            vStoreName.setContentText(currentStoreInfo.getName());
            vStoreName.setSelectionLast();
            vStoreCategory.setContentText(currentStoreInfo.getMainBusinessCategoryNames());
            String cityStr = currentStoreInfo.getCityStr();
            if (cityStr != null) {
                cityStr = cityStr.trim();
            }
            vCity.setContentText(cityStr);
            vMarket.setContentText(currentStoreInfo.getMarketName());
            vMarketArea.setContentText(currentStoreInfo.getAreaName());
            vDescription.setContentText(currentStoreInfo.getDescription());
            marketName = currentStoreInfo.getMarketName();
            vMarket.setContentText(marketName);
            vMarketId.setContentText(currentStoreInfo.getStall());
//            ssOrder.setState(currentStoreInfo.isOpen());
            cityId = currentStoreInfo.getCityId();
            districtId = currentStoreInfo.getDistrictId();
            provinceId = currentStoreInfo.getProvinceId();
            marketId = currentStoreInfo.getMarketId();
            marketAreaId = currentStoreInfo.getAreaId();
            vStoreAvater.setPhotoId(currentStoreInfo.getHeaderImageId());
            if (logoUrl != null && !"".equals(logoUrl))
                ImageLoader.getInstance().displayImage(logoUrl, vStoreAvater.getImagView());
            if ((TYPE == Constant.TYPE_STORE_STATUS_PRVIEW || TYPE == Constant.TYPE_STORE_STATUS_PRVIEW_EDIT) && currentStoreInfo.getTag() != null && currentStoreInfo.getTag().size() > 0) {
//                rlTag.setVisibility(View.VISIBLE);
//                tvtTag.setCommTags(currentStoreInfo.getTag());
            }
//            if ((TYPE == Constant.TYPE_STORE_STATUS_PRVIEW || TYPE == Constant.TYPE_STORE_STATUS_PRVIEW_EDIT)) {
//
//                if (currentStoreInfo.getStall() == null || "".equals(currentStoreInfo.getStall())){
//                    vMarketId.setContentText("临时铺位");
//                }
//            }
//            List<PickUpAddressesEntity> pickUpAddresses = currentStoreInfo.getPickUpAddresses();
//            if (pickUpAddresses != null && pickUpAddresses.size() > 0) {
//                PickUpAddressesEntity pickUpAddressesEntity = pickUpAddresses.get(0);
//
//            } else {
//
//            }
//
//            List<Images> images = currentStoreInfo.getImages();
//            if (images != null && images.size() > 0) {
//
//            } else {
//
//
//            }
            if (!TextUtils.isEmpty(currentStoreInfo.getLastAuditMark())) {
                rlRefuse.setVisibility(View.VISIBLE);
                tvRefuse.setText(currentStoreInfo.getLastAuditMark());
            }
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putInt(Constant.KEY_STORE_TYPE_STATUS, TYPE);
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {

            case R.id.ci_detail_pic:
                intoDetailPicPage();
                break;
            case R.id.ci_city:
                if (toIndex==2) {
                    toast("不能修改所在城市");
                    break;
                }
                intoAddressPage();
                break;
            case R.id.rl_store_avater:
                photoCore.showPhotoDialog(Uri.fromFile(new File(filePath)), filePath, vStoreAvater.isFail());
                break;
            case R.id.tv_btn:
//                if (TYPE == Constant.TYPE_STORE_STATUS_PRVIEW_EDIT) {
//                    dealActionPreview();
//                } else {
                dealAction();
//                }
                break;
            case R.id.v_receive:
//                dealSwitch();
                break;
            case R.id.ci_market_address:
                if (toIndex==2) {
                    toast("不能修改所在市场");
                    break;
                }
                openStoreMarket(cityId, districtId);
                break;
            case R.id.rightbtn:
                help();
                break;
            case R.id.tv_save_cache:
                saveCache();
                break;
            case R.id.ci_store_category:
//                showStoreCategory();
                requestStoreCategory();
                break;
            case R.id.ci_market_area:

                if (TextUtils.isEmpty(cityId)) {
                    toast("请选择您店铺所在的城市");
                    return;
                }
                if (TextUtils.isEmpty(marketId)) {
                    toast("请选择所在的批发市场");
                    return;
                }
                requestMarketArea(marketId);
                break;
        }
    }

    private void showStoreCategory() {

        if (categoryTag.getVisibility() == View.GONE) {
            categoryTag.setVisibility(View.VISIBLE);
            vStoreCategory.getIvFlag().setImageResource(R.mipmap.top_arrow);

            //主营分类初始化
            String mbci = currentStoreInfo.getMainBusinessCategoryIds();

            Set<Integer> set = new HashSet<>();
            if (mbci != null && !"".equals(mbci)) {
                String[] split = mbci.split(",");
                if (split != null && split.length > 0) {
                    for (int i = 0; i < split.length; i++) {
                        String s = split[i];
                        if (s != null) {
                            for (int j = 0; j < listCategory.size(); j++) {
                                Category category = listCategory.get(j);
                                String id = category.getId();
                                if (s.equals(id)) {
                                    set.add(j);
                                }
                            }
                        }
                    }

                    adapter.setSelectedList(set);
                }
            }
        } else {
            vStoreCategory.getIvFlag().setImageResource(R.mipmap.bottom_arrow);
            categoryTag.setVisibility(View.GONE);
        }
    }

    private void saveCache() {
        String storeName = vStoreName.getContentText();
        if (TextUtils.isEmpty(storeName)) {
            toast("请填写店铺名称");
            return;
        }
        if (isContentEmpty()) {
            toast("请填写信息");
            return;
        }
        String picId = vStoreAvater.getPhotoId();
        if (!TextUtils.isEmpty(picId)) {
//            currentStoreInfo.setLogo(picId + "");
            currentStoreInfo.setHeaderImageId(picId + "");
        } else {
//            currentStoreInfo.setLogo(null);
        }
        currentStoreInfo.setName(vStoreName.getContentText());

        currentStoreInfo.setDescription(vDescription.getContentText());
//        currentStoreInfo.setProvinceId(provinceId);
//        currentStoreInfo.setDistrictId(districtId);
//        currentStoreInfo.setCityId(cityId);

//      currentStoreInfo.setMarketName(market);
//        currentStoreInfo.setMarketName(null);

        currentStoreInfo.setStall(marketId);

//        if (isFirst) {
//            currentStoreInfo.setPickUpAddresses(listPickupAddress);
//        }
//        currentStoreInfo.setMarketId(marketId);
        L.d("imagssss", "imagssss:" + currentStoreInfo.getImages());
//        currentStoreInfo.setImages(listDetailImage);
        if (isFirst) {
            uploadStore(currentStoreInfo, true);
        }
    }

    private void help() {
        Intent intent = new Intent(this, WebActivity.class);
        intent.putExtra(Constant.KEY_WEB_URL, Constant.URL_HELP_STORE_CERT);
        intent.putExtra(Constant.KEY_WEB_TITLE, getString(R.string.help));
        startActivity(intent);
    }


    @Override
    protected void onStart() {
        if (isFirst) {
            updatePickupCount();
            updateImagesCount();
        }
        super.onStart();
    }

    List<PickUpAddressesEntity> listPickupAddress;

    public void updatePickupCount() {
        SharedPreferences sp = FileUtil.getSharedPreferences();
        String str = sp.getString(Constant.KEY_PICK_UP_ADDRESS + "_" + getUser().getAccountId(), "");
        if (!TextUtils.isEmpty(str)) {
            List<PickUpAddressesEntity> list = new Gson().fromJson(str, new TypeToken<List<PickUpAddressesEntity>>() {
            }.getType());

            if (list == null || list.size() < 1) {
                //没有本地地址存储


            } else {
                if (listPickupAddress == null) {
                    listPickupAddress = new ArrayList<>();
                }
                listPickupAddress.clear();
                listPickupAddress.addAll(list);
                if (isFirst) {
                    currentStoreInfo.setPickUpAddressSize(listPickupAddress.size() + "");
                    currentStoreInfo.setPickUpAddresses(listPickupAddress);
                }

                List<PickUpAddressesEntity> pickUpAddresses = currentStoreInfo.getPickUpAddresses();
                if (pickUpAddresses != null && pickUpAddresses.size() > 0) {
                    PickUpAddressesEntity pickUpAddressesEntity = pickUpAddresses.get(0);

                } else {

                }
            }
        }
    }

    List<Images> listDetailImage;

    public void updateImagesCount() {
        SharedPreferences sp = FileUtil.getSharedPreferences();
        String str = sp.getString(Constant.KEY_STORE_DETAIL_IMAGE_ADDRESS + "_" + getUser().getAccountId(), "");
        if (!TextUtils.isEmpty(str)) {
            List<Images> list = new Gson().fromJson(str, new TypeToken<List<Images>>() {
            }.getType());

            if (list == null || list.size() < 1) {
                //没有本地地址存储


            } else {
                if (listDetailImage == null) {
                    listDetailImage = new ArrayList<>();
                }
                listDetailImage.clear();
                listDetailImage.addAll(list);
//                vDetailPic.setContentText(listDetailImage.size() + "");
            }
        }
    }

    CustomDialog.Builder builder;

    private void openDialog() {
        if (builder == null) {
            builder = new CustomDialog.Builder(mContext);
            builder.setTitleVisible(false).setMessage("如果您已填写信息，返回后信息将不被保存，是否返回？")//
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {//添加确定按钮
                        @Override
                        public void onClick(DialogInterface dialog, int which) {//确定按钮的响应事件
                            finish();
                            dialog.dismiss();
                        }
                    }).setNegativeButton("取消", new DialogInterface.OnClickListener() {//添加返回按钮
                @Override
                public void onClick(DialogInterface dialog, int which) {//响应事件
                    dialog.dismiss();
                }

            });//在按键响应事件中显示此对话框
        }
        builder.create().show();

    }

    @Override
    public void onBackPressed() {
        //  super.onBackPressed();
        if (toIndex!=2) {
            intoLogin();
        } else {
            finish();
        }
    }

    @Override
    protected void onToolbarBack() {
        onBackPressed();
    }


//    public boolean isEmptyContent() {
//        String picId = vStoreAvater.getPhotoId();
//        if (!TextUtils.isEmpty(currentStoreInfo.getLogoUrl()) || !TextUtils.isEmpty(picId)) {
//            return false;
//        }
//
//        String storeName = vStoreName.getContentText();
//        if (!TextUtils.isEmpty(storeName)) {
//            return false;
//        }
//
//
//        String market = vMarket.getContentText();
//        if (!TextUtils.isEmpty(market)) {
//            return false;
//        }
//
//
//        String description = vDescription.getContentText();
//        if (!TextUtils.isEmpty(description)) {
//            return false;
//        }
//
//
//        return true;
//    }

    //    private void dealSwitch() {
//        if (builder == null) {
//            builder = new CustomDialog.Builder(mContext);
//            builder.setTitleVisible(false).setMessage("设置成不接单？")//设置显示的内容
//                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {//添加确定按钮
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {//确定按钮的响应事件
//                            dealSwitch(false);
//                            dialog.dismiss();
//                        }
//                    }).setNegativeButton("取消", new DialogInterface.OnClickListener() {//添加返回按钮
//                @Override
//                public void onClick(DialogInterface dialog, int which) {//响应事件
//                    dialog.dismiss();
//                }
//
//            });//在按键响应事件中显示此对话框
//        }
//        if (ssOrder.isOpen()) {
//            builder.create().show();
//        } else {
//            dealSwitch(true);
//        }
//
//    }

//    int type = -1;
//
//    private void dealActionPreview() {
//        if (type == -1) {
//            edit();
//            type = 1;
//        } else {
//            dealAction();
//        }
//
//    }

    private boolean isContentEmpty() {
//        boolean isContentEmpty = true;
        String picId = vStoreAvater.getPhotoId();
        if (!TextUtils.isEmpty(currentStoreInfo.getHeaderImageUrl()) || !TextUtils.isEmpty(picId)) {
            return false;
        }

        String storeName = vStoreName.getContentText();
        if (!TextUtils.isEmpty(storeName)) {
            return false;
        }

        String storeCategory = vStoreCategory.getContentText();
        if (!TextUtils.isEmpty(storeCategory)) {
            return false;
        }

        String city = vCity.getContentText();

        if (!TextUtils.isEmpty(city)) {
            return false;
        }

        String market = vMarket.getContentText();
        if (!TextUtils.isEmpty(market)) {
            return false;
        }
        String marketArea = vMarketArea.getContentText();
        if (!TextUtils.isEmpty(marketArea)) {
            return false;
        }
        String marketId = vMarketId.getContentText();
        if (!TextUtils.isEmpty(marketId)) {
            return false;
        }

        String description = vDescription.getContentText();
        if (!TextUtils.isEmpty(description)) {
            return false;
        }

        return true;
    }

    private void dealAction() {

        String picId = vStoreAvater.getPhotoId();
        if (!TextUtils.isEmpty(currentStoreInfo.getHeaderImageUrl()) || !TextUtils.isEmpty(picId)) {

        } else {
            toast("请上传店铺门头照");
            return;
        }

        String storeName = vStoreName.getContentText();
        if (TextUtils.isEmpty(storeName)) {
            toast("请填写您的店铺名称");
            return;
        }
        if (!VerificationUtils.isValid(storeName)) {
            toast(getString(R.string.illegal_input, "店铺名称"));
            return;
        }
        String storeCategory = vStoreCategory.getContentText();
        if (TextUtils.isEmpty(storeCategory)) {
            toast("请选择您的经营范围");
            return;
        }

        String city = vCity.getContentText();

        if (TextUtils.isEmpty(city)) {
            toast("请选择您店铺所在的城市");
            return;
        }

        String market = vMarket.getContentText();
        if (TextUtils.isEmpty(market)) {
            toast("请选择所在的批发市场");
            return;
        }
        String marketArea = vMarketArea.getContentText();
        if (TextUtils.isEmpty(marketArea)) {
            toast("请选择您经营范围所在的市场分区");
            return;
        }
        String marketId = vMarketId.getContentText();
        if (TextUtils.isEmpty(marketId)) {
            toast("请填写档口号");
            return;
        }

        if (!VerificationUtils.isValid(marketId)) {
            toast(getString(R.string.illegal_input, "档口号码"));
            return;
        }

        String description = vDescription.getContentText();
        if (TextUtils.isEmpty(description)) {
            toast("请填写简介");
            return;
        }
        if (!VerificationUtils.isValid(description)) {
            toast(getString(R.string.illegal_input, "简介"));
            return;
        }
//        if (TextUtils.isEmpty(vOwnAddress.getContentText())) {
//            toast("请填写提货地址");
//            return;
//        }
//        if (TextUtils.isEmpty(currentStoreInfo.getPickUpAddressSize())||"0".equals(currentStoreInfo.getPickUpAddressSize())) {
//            toast("请填写提货地址");
//            return;
//        }


//      currentStoreInfo = new StoreBaseInfo();
//        String provinceId = this.provinceId;
//        String cityId = this.cityId;
//        String districtId = this.districtId;

        if (!TextUtils.isEmpty(picId)) {
            currentStoreInfo.setHeaderImageId(picId + "");
        } else {
//            currentStoreInfo.setLogo(null);
        }
        currentStoreInfo.setName(storeName);

        currentStoreInfo.setDescription(description);
//        currentStoreInfo.setProvinceId(provinceId);
//        currentStoreInfo.setDistrictId(districtId);
//        currentStoreInfo.setCityId(cityId);

//      currentStoreInfo.setMarketName(market);
//        currentStoreInfo.setMarketName(null);

        currentStoreInfo.setStall(marketId);

//        if (isFirst) {
//            currentStoreInfo.setPickUpAddresses(listPickupAddress);
//        }
//        currentStoreInfo.setMarketId(marketId);
        L.d("imagssss", "imagssss:" + currentStoreInfo.getImages());
//        currentStoreInfo.setImages(listDetailImage);
        if (isFirst) {
            uploadStore(currentStoreInfo, false);
        } else {
            modifyStore(currentStoreInfo);
        }

    }

    private void intoDetailPicPage() {
        Intent intent = new Intent(this, UploadStorePictureActivity.class);
        if (isFirst) {
            intent.putExtra(Constant.TYPE, true);
        }

        List<Images> images = currentStoreInfo.getImages();
        L.e("images", "store_images:" + images);
        if (images != null && images.size() > 0) {
            String pics = new Gson().toJson(images);
            intent.putExtra(Constant.KEY_STORE_DETAIL_IMAGE_ADDRESS, pics);
        }


        startActivityForResult(intent, 0x40);

    }


    private void intoSelectAddressPage() {

        if (isFirst) {
            Intent intent = new Intent(this, MyPickupAddressActivity.class);
            startActivity(intent);
        } else {
            Intent intent = new Intent(this, MyAddressActivity.class);
            startActivityForResult(intent, 0x89);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        DataManager.getInstance().setCertInfo(null);
        if (isFirst) {
            SharedPreferences sp = FileUtil.getSharedPreferences();
            String str = sp.getString(Constant.KEY_PICK_UP_ADDRESS + "_" + getUser().getAccountId(), "");
            if (!TextUtils.isEmpty(str)) {
                SharedPreferences.Editor edit = sp.edit();
                edit.putString(Constant.KEY_PICK_UP_ADDRESS + "_" + getUser().getAccountId(), "");
                edit.commit();
            }
        }
    }

    private String provinceId = "";
    private String cityId = "";
    private String districtId = "";
    private String provinceName = "";
    private String cityName = "";
    private String districtName = "";
    private int RES_CODE = 0x010;


    private void intoAddressPage() {
        findCity();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (/*resultCode == RESULT_OK && */requestCode == RES_CODE) {
            if (data != null) {
                if (cityId != null && cityId.equals(data.getStringExtra("cityCode"))) {

                } else {
                    vMarket.setContentText("");
                }
                cityName = data.getExtras().getString("name");
                provinceId = data.getStringExtra("provinceCode");
                cityId = data.getStringExtra("cityCode");
                districtId = data.getStringExtra("areaCode");

                L.i("test", provinceId + "," + cityId + "," + districtId);
            }
        } else if (resultCode == RESULT_OK && requestCode == 0x40) {
            // 详情图片返回
            String img = data.getStringExtra(Constant.KEY_STORE_DETAIL_IMAGE_ADDRESS);
            if (!TextUtils.isEmpty(img)) {
                List<Images> imagesList = new Gson().fromJson(img, new TypeToken<List<Images>>() {
                }.getType());
                currentStoreInfo.setImages(imagesList);
                L.e("images", "store_images222:" + imagesList);

            } else {

            }
        } else if (resultCode == RESULT_OK && requestCode == 0x89) {
            // 详情图片返回
            int count = data.getIntExtra("count_pick_up", -1);
            String address = data.getStringExtra("pick_up_address");

            if (count > -1) {
                currentStoreInfo.setPickUpAddressSize(address);

//                vOwnAddress.setSelect(true);
            } else {

                currentStoreInfo.setPickUpAddressSize("");

            }
        }
        photoCore.onResult(requestCode, resultCode, data);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        photoCore.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }


    @Override
    public void onSuccess(String path) {
        vStoreAvater.showImage();
        tag.type = RequestTag.TYPE_CURRENT;
        currentLogoPath = path;
        ImageSize imageSize = new ImageSize(200, 200);
        Log.e("sfsaf", "" + path);
        ImageLoader.getInstance().displayImage(path, new ImageViewAware(vStoreAvater.getImagView()), vStoreAvater.getImageOption(), imageSize, null, null);
        vStoreAvater.uploadImage(this, filePath, tag);
    }

    @Override
    public void onFail(String msg) {
        toast("获取图片失败");
    }

    @Override
    public void onReupload() {
        tag.type = RequestTag.TYPE_CURRENT;
        vStoreAvater.uploadImage(this, filePath, tag);
    }


    private OnRequestListener<StatusEntity> onAddRequestListener = new OnRequestListener<StatusEntity>() {
        @Override
        public StatusEntity jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, StatusEntity.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            hideProgressDialog();

        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            hideProgressDialog();

        }

        @Override
        public void onStart(Object tag) {
            showProgressDialog();
        }

        @Override
        public void onResponse(ResponseEntity<StatusEntity> response, Object tag) {

//            hideProgressDialog();
            StatusEntity responseElement = response.getResponseElement();

            if (responseElement.isSuccess()) {
//                toast(BaseApplication.getDoc().getInfoChecking());
//                addStoreSuccess();
                boolean isScratch = false;
                if (tag != null && tag instanceof RequestTag) {
                    RequestTag rt = (RequestTag) tag;
                    isScratch = rt.action == 0 ? false : true;

                }
                merchantId = responseElement.getMerchantId();
                if (isFirst && !isScratch) {

                    getCertInfo();
                } else {//暂存
                    hideProgressDialog();
                    toast("保存成功");
                }


            } else {
                hideProgressDialog();
                toast("提交失败请稍后再试");
            }
        }
    };

    private OnRequestListener<StatusEntity> onRequestListener = new OnRequestListener<StatusEntity>() {
        @Override
        public StatusEntity jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, StatusEntity.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            hideProgressDialog();

        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            hideProgressDialog();

        }

        @Override
        public void onStart(Object tag) {
            showProgressDialog();
        }

        @Override
        public void onResponse(ResponseEntity<StatusEntity> response, Object tag) {

            hideProgressDialog();
            StatusEntity responseElement = response.getResponseElement();

            if (responseElement.isSuccess()) {

               /* if (type == 1) {
                    previewEdit();
                    type = -1;
                    updateStoreInfo();
                    toast(BaseApplication.getDoc().getSaved());
                } else*/
                if (isFirst) {
                    toast(BaseApplication.getDoc().getInfoChecking());
                    addStoreSuccess();
                } else {
                    if (getStoreInfo() == null || getStoreInfo().getStore() == null) {
                        toast("数据错误，请刷新后重试");
                        return;
                    }
                    Store store = getStoreInfo().getStore();
                    if (store != null) {
                        store.setName(currentStoreInfo.getName());
                        store.setHeaderImageUrl(currentStoreInfo.getHeaderImageUrl());
                        if (TYPE == Constant.TYPE_STORE_STATUS_EDIT) {//再次编辑
                            store.setAuditStatus("0");
                        }
                        updateStoreInfo(getStoreInfo());
                        String auditStatus = store.getAuditStatus();
                        //审核被拒，调用审核被拒接口
//                        if ("2".equals(auditStatus)) {
//                            applyAudit();
//                        }
                    }
                    setResult(RESULT_OK);
                    finish();
                }
            } else {
                toast("服务器处理失败");
            }
        }
    };
    private OnRequestListener<CertInfo> onCertInfoRequestListener = new OnRequestListener<CertInfo>() {
        @Override
        public CertInfo jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, CertInfo.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            hideProgressDialog();

            if (failCode == HttpRequest.FAIL_JSON_PARSER) {
                intoIDCart(null);
            } else {
                toast(arg + "");
            }
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            hideProgressDialog();
            toast(arg + "");
        }

        @Override
        public void onStart(Object tag) {

        }

        @Override
        public void onResponse(ResponseEntity<CertInfo> response, Object tag) {

            hideProgressDialog();
            CertInfo ci = response.getResponseElement();

            DataManager.getInstance().setCertInfo(ci);
            intoCertView(ci);

        }
    };

    private void intoCertView(CertInfo ci) {
        if (ci != null) {
            if (ci.hasCert()) {//是否认证过
                if (ci.isPostCert()) { //是否是提交审核，true，直接跳银行卡
                    //  intoBankCart(ci);
                    intoIDCart(ci);
                } else {//跳认证选择页面
                    intoIDCart(ci);
                }
            } else {
                intoIDCart(ci);
            }
        }

    }

    private void intoIDCart(CertInfo ci) {
        //Intent intent = new Intent(this,EnsureCompanyActivity.class);
        if (ci == null || ci.getType() == null || ci.getType().equals("0")) {
            Intent intent = new Intent(this, EnsurePersonActivity.class);
            if (ci != null)
                intent.putExtra("certInfo", new Gson().toJson(ci));
            intent.putExtra("isFirst", isFirst);
            intent.putExtra("merchantId", merchantId);
            intent.putExtra("remark", currentStoreInfo.getLastAuditMark());
            startActivity(intent);
        } else {
            Intent intent = new Intent(this, EnsureCompanyActivity.class);
            if (ci != null)
                intent.putExtra("certInfo", new Gson().toJson(ci));
            intent.putExtra("isFirst", isFirst);
            intent.putExtra("merchantId", merchantId);
            intent.putExtra("remark", currentStoreInfo.getLastAuditMark());
            startActivity(intent);
        }

    }

    private void intoBankCart(CertInfo ci) {
        Intent bank = new Intent(this, BankActivity.class);
        bank.putExtra("card_count", getStoreInfo().getBankCardCount());
        bank.putExtra(Constant.TYPE, -1);
        bank.putExtra("isFirst", isFirst);
        bank.putExtra("userType", "1".equals(ci.getType()) ? 1 : 2);
        bank.putExtra("merchantId", merchantId);
        startActivity(bank);
    }


    private void addStoreSuccess() {
        if (getStoreInfo() == null || getStoreInfo().getStore() == null) {
            toast("数据错误，请刷新后重试");
            return;
        }
        Store store = getStoreInfo().getStore();
        if (store != null) {
            store.setAuditStatus("0");
        } else {
            store = new Store();
            store.setAuditStatus("0");
        }
        if (store != null) {
            store.setName(currentStoreInfo.getName());
            store.setHeaderImageUrl(currentStoreInfo.getHeaderImageUrl());
        }
        getStoreInfo().setStore(store);
        updateStoreInfo(getStoreInfo());

        L.d("store", "storeactivity:" + getStoreInfo());
        if (getStoreInfo().isOpenStore()) {

        } else {

        }
        if (currentLogoPath != null && !"".equals(currentLogoPath))
            currentStoreInfo.setHeaderImageUrl(currentLogoPath);
        Intent intent = new Intent(this, StoreEnsureAndOpenActivity.class);
        startActivity(intent);
//        Intent intent = new Intent(this, BankActivity.class);
//        startActivity(intent);
    }

    private OnRequestListener<ContentEntity<Market>> onMarketRequestListener = new OnRequestListener<ContentEntity<Market>>() {
        @Override
        public ContentEntity<Market> jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, new TypeToken<ContentEntity<Market>>() {
            }.getType());
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            hideProgressDialog();

        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {

            hideProgressDialog();
        }

        @Override
        public void onStart(Object tag) {
            showProgressDialog();
        }

        @Override
        public void onResponse(ResponseEntity<ContentEntity<Market>> response, Object tag) {

            hideProgressDialog();
            ContentEntity<Market> responseElement = response.getResponseElement();
            if (responseElement != null && responseElement.getContent() != null && responseElement.getContent().size() > 0) {
                openStoreMarket(responseElement.getContent());
            } else {
                //没有数据
                toast("当前地区没有市场");
            }

        }
    };
    private String cmdStoreInfo = "store/info";
    RequestTag tag = new RequestTag();
    int picId = Integer.MIN_VALUE;
    OnRequestListener<FileUploadResponse> uploadListener = new OnRequestListener<FileUploadResponse>() {
        @Override
        public FileUploadResponse jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, FileUploadResponse.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {

            switch (failCode) {
                case HttpRequest.FAIL_NOT_FOUND:

                    break;
                case HttpRequest.FAIL_NO_NET:

                    break;
                case HttpRequest.FAIL_NET_FAULT:

                default:

                    break;
            }

            vStoreAvater.showFail();
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {

            vStoreAvater.showFail();
        }

        @Override
        public void onStart(Object tag) {
            picId = Integer.MIN_VALUE;
            vStoreAvater.showProgress();
        }

        @Override
        public void onResponse(ResponseEntity<FileUploadResponse> response, Object tag) {
            vStoreAvater.showImage();

            FileUploadResponse responseElement = response.getResponseElement();
            int id = responseElement.getId();
            picId = id;
            if (id == Integer.MIN_VALUE) {
                toast("图片上传失败");
                return;
            }

        }
    };


    //第一次开店上传数据
    public void uploadStore(StoreBaseInfo storeBaseInfo, boolean isScratch) {

        RequestEntitySupply<StoreBaseInfo> RequestEntitySupply = new RequestEntitySupply<>();
        RequestEntitySupply.setCmd(com.epfresh.api.constant.AppSupplyRouterConstant.cmd_store_store_modify);
        if (storeBaseInfo != null) {
            storeBaseInfo.setAuditStatus(storeBaseInfo.getAuditStatus());
            storeBaseInfo.setHeaderImageUrl(null);
        }
        RequestEntitySupply.setParameters(storeBaseInfo);
        RequestTag tag = new RequestTag();
        tag.tag = com.epfresh.api.constant.AppSupplyRouterConstant.cmd_store_store_modify;
//        tag.type = RequestTag.TYPE_CURRENT;
        tag.action = isScratch ? 1 : 0;
        request(RequestEntitySupply, tag, onAddRequestListener);

    }

    public void modifyStore(StoreBaseInfo storeBaseInfo) {

        RequestEntitySupply<StoreBaseInfo> RequestEntitySupply = new RequestEntitySupply<>();
        RequestEntitySupply.setCmd(com.epfresh.api.constant.AppSupplyRouterConstant.cmd_store_store_modify);
        if (storeBaseInfo != null) {
            storeBaseInfo.setAuditStatus(null);
        }
        if (TYPE == Constant.TYPE_STORE_STATUS_EDIT) {//再次编辑
            storeBaseInfo.setAuditStatus("0");
        }
        RequestEntitySupply.setParameters(storeBaseInfo);
        request(RequestEntitySupply, com.epfresh.api.constant.AppSupplyRouterConstant.cmd_store_store_modify, onRequestListener);

    }

    public void getCertInfo() {

        RequestEntityMapSupply RequestEntitySupply = new RequestEntityMapSupply();
        RequestEntitySupply.setCmd(com.epfresh.api.constant.AppSupplyRouterConstant.cmd_account_merchant_cert);

        RequestEntitySupply.putParameter("merchantId", merchantId);

        RequestTag tag = new RequestTag();
        tag.type = RequestTag.TYPE_CURRENT;
        request(RequestEntitySupply, tag, onCertInfoRequestListener);

    }

    public void requestUnPostStoreInfo() {

        RequestEntitySupply<Object> RequestEntitySupply = new RequestEntitySupply<>();
        RequestEntitySupply.setCmd(com.epfresh.api.constant.AppSupplyRouterConstant.cmd_store_store_load4supplier);
        RequestTag tag = new RequestTag();
        tag.type = RequestTag.TYPE_CURRENT;

        tag.arg1 = com.epfresh.api.constant.AppSupplyRouterConstant.cmd_store_store_load4supplier;
        request(RequestEntitySupply, tag, onRequestUnPostListener);

    }


    private OnRequestListener<StoreBaseInfo> onRequestUnPostListener = new OnRequestListener<StoreBaseInfo>() {
        @Override
        public StoreBaseInfo jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, StoreBaseInfo.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            hideProgressDialog();
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            hideProgressDialog();
        }

        @Override
        public void onStart(Object tag) {
            showProgressDialog();
        }

        @Override
        public void onResponse(ResponseEntity<StoreBaseInfo> response, Object tag) {

            hideProgressDialog();
            currentStoreInfo = response.getResponseElement();
            if (currentStoreInfo != null) {
//                marketName = currentStoreInfo.getMarketName();
                currentStoreInfo.initMarket();
            }
            updateStoreInfo();
            if (TYPE == Constant.TYPE_STORE_STATUS_PRVIEW) {//预览
                preview();
            } else if (TYPE == Constant.TYPE_STORE_STATUS_PRVIEW_EDIT) {//
                previewEdit(false);
            }

        }
    };


    City cityData;

    public void openArea() {
        AreaDialog areaDialog = new AreaDialog(this);
        if (cityData == null)
            cityData = areaDialog.getCityData();
        areaDialog.setPositiveDismiss(true);
        areaDialog.setCurrentIndex(cityData, provinceId, cityId, districtId);
        areaDialog.setOnPositiveClickListener(new AreaDialog.OnPositiveClickListener() {

            @Override
            public void onPositiveClickListener(int index1, CityAddressList city1, int index2, CityAddressList city2, int index3, CityAddressList city3) {
                if (city1 != null && city2 != null) {
                    if (
                            (provinceId != null && provinceId.equals(city1.getCode()))
                                    &&
                                    (cityId != null && cityId.equals(city2.getCode()))
                                    &&
                                    (districtId != null && districtId.equals(city3.getCode()))


                            ) {


                    } else {
                        vMarket.setContentText("");
                        vMarketArea.setContentText("");
                        vMarketId.setContentText("");
                        currentStoreInfo.setMarketName(null);
                        currentStoreInfo.setMarketId(null);
                        currentStoreInfo.setAreaId(null);
                        currentStoreInfo.setAreaName(null);

                        currentStoreInfo.setStall(null);
                        marketAreaId = null;
                        marketAreaName = null;
                        marketId = null;
                        marketName = null;

                    }
                    if (city3 != null) {
                        cityName = city1.getName() + " " + city2.getName() + " " + city3.getName();
                        districtId = city3.getCode();
                        currentStoreInfo.setDistrictId(districtId);
                    } else {
                        cityName = city1.getName() + " " + city2.getName();
                    }
//                    cityName = city1.getName() + city2.getName() + city3.getName();
                    provinceId = city1.getCode();
                    cityId = city2.getCode();
                    currentStoreInfo.setProvinceId(provinceId);
                    currentStoreInfo.setCityId(cityId);
                    vCity.setContentText(cityName);
                }
            }
        });
        areaDialog.show();
    }


    //    private ArrayList<Market> options1Items = new ArrayList<Market>();
//    private WheelDialog pvOptions;
//
    private String marketId;
    private String marketName;

    private MarketDialog marketDialog;

    public void openStoreMarket(List<Market> markets) {

        if (marketDialog == null) {
            marketDialog = new MarketDialog(this);
            marketDialog.setPositiveDismiss(true);

            marketDialog.setOnPositiveClickListener(new MarketDialog.OnPositiveClickListener() {
                @Override
                public void onPositiveClickListener(int index, Market market) {
                    String id = market.getId();
                    if (id != null && id.equals(currentStoreInfo.getMarketId())) {
//                        return;
                    } else {
                        currentStoreInfo.setAreaId(null);
                        currentStoreInfo.setAreaName(null);
                        marketAreaId = null;
                        marketAreaName = null;
                        vMarketArea.setContentText("");
                    }
                    vMarket.setContentText(market.getName());
                    marketId = id;
                    marketName = market.getName();
                    currentStoreInfo.setMarketId(marketId);
                    currentStoreInfo.setMarketName(marketName);
                }
            });

        }
        marketDialog.setCurrent(markets, marketId);
        marketDialog.show();

    }

    private String marketAreaId;
    private String marketAreaName;

    private MarketDialog marketAreaDialog;

    public void openStoreMarketArea(List<Market> markets) {

        if (marketAreaDialog == null) {
            marketAreaDialog = new MarketDialog(this);
            marketAreaDialog.setPositiveDismiss(true);

            marketAreaDialog.setTitle("市场分区");
            marketAreaDialog.setOnPositiveClickListener(new MarketDialog.OnPositiveClickListener() {
                @Override
                public void onPositiveClickListener(int index, Market market) {
                    vMarketArea.setContentText(market.getName());
                    marketAreaId = market.getId();
                    marketAreaName = market.getName();
                    currentStoreInfo.setAreaId(marketAreaId);
                    currentStoreInfo.setAreaName(marketAreaName);
                }
            });

        }
        marketAreaDialog.setCurrent(markets, marketAreaId);
        marketAreaDialog.show();

    }

    class ResponseList {
        private ArrayList<CityAddressList> response;
        String serverTime;
        String statusCode;

        public ArrayList<CityAddressList> getResponse() {
            return response;
        }

        public void setResponse(ArrayList<CityAddressList> response) {
            this.response = response;
        }

        public String getServerTime() {
            return serverTime;
        }

        public void setServerTime(String serverTime) {
            this.serverTime = serverTime;
        }

        public String getStatusCode() {
            return statusCode;
        }

        public void setStatusCode(String statusCode) {
            this.statusCode = statusCode;
        }
    }

    OnRequestListener<City> onRequestListenerCity = new OnRequestListener<City>() {
        @Override
        public City jsonToObj(String responseStr) {
            //return new Gson().fromJson(responseStr, City.class);
            ArrayList<CityAddressList> addressLists = JsonUtils.fromJsonList(responseStr, CityAddressList.class);
            City city = new City();
            city.setTree(addressLists);
            return city;

/*            public List<CouponEntity> jsonToObj(String responseStr) {
                return new Gson().fromJson(responseStr, new TypeToken<List<CouponEntity>>() {
                }.getType());
            }*/
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            hideProgressDialog();
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {

            hideProgressDialog();
        }

        @Override
        public void onStart(Object tag) {


            showProgressDialog();
        }

        @Override
        public void onResponse(ResponseEntity<City> response, Object tag) {

            hideProgressDialog();
            City responseElement = response.getResponseElement();

            if (responseElement != null) {
                cityData = responseElement;
                openArea();
            }
        }
    };

    public void findCity() {
        RequestEntityMapSupply re = new RequestEntityMapSupply();
        re.setCmd(com.epfresh.api.constant.AppSupplyRouterConstant.cmd_account_app_openCity);

        re.putParameter("version", -1);

        request(re, com.epfresh.api.constant.AppSupplyRouterConstant.cmd_account_app_openCity, onRequestListenerCity);
    }


    public void openStoreMarket(String cityId, String districtId) {
        if (TextUtils.isEmpty(cityId)) {
            toast("请选择您店铺所在的城市");
            return;
        }
        RequestEntitySupply<Map<String, String>> RequestEntitySupply = new RequestEntitySupply<>();
        RequestEntitySupply.setCmd(com.epfresh.api.constant.AppSupplyRouterConstant.cmd_store_store_market_list);
        Map<String, String> map = new HashMap<>();
        map.put("cityId", cityId);
        map.put("districtId", districtId);
        RequestEntitySupply.setParameters(map);
        request(RequestEntitySupply, com.epfresh.api.constant.AppSupplyRouterConstant.cmd_store_store_market_list, onMarketRequestListener);
    }

    private OnRequestListener<List<Category>> onStoreCategoryRequestListener = new OnRequestListener<List<Category>>() {
        @Override
        public List<Category> jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, new TypeToken<List<Category>>() {
            }.getType());
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {

            hideProgressDialog();
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {

            hideProgressDialog();
        }

        @Override
        public void onStart(Object tag) {
            showProgressDialog();
        }

        @Override
        public void onResponse(ResponseEntity<List<Category>> response, Object tag) {

            hideProgressDialog();
            List<Category> responseElement = response.getResponseElement();

            if (responseElement != null) {
                listCategory.clear();
                listCategory.addAll(responseElement);
                adapter.notifyDataChanged();
                showStoreCategory();
            }

        }
    };

    public void requestStoreCategory() {
//        category/getTopCategories
//        if (categoryTag.getVisibility() == View.GONE) {
//            categoryTag.setVisibility(View.VISIBLE);
//            vStoreCategory.getIvFlag().setImageResource(R.mipmap.top_arrow);
//        } else {
//            vStoreCategory.getIvFlag().setImageResource(R.mipmap.bottom_arrow);
//            categoryTag.setVisibility(View.GONE);
//        }
        if (listCategory.size() == 0 && categoryTag.getVisibility() == View.GONE) {
            RequestEntitySupply<Map<String, String>> RequestEntitySupply = new RequestEntitySupply<>();
            RequestEntitySupply.setCmd(com.epfresh.api.constant.AppSupplyRouterConstant.cmd_store_category_getTopCategories);

            request(RequestEntitySupply, com.epfresh.api.constant.AppSupplyRouterConstant.cmd_store_category_getTopCategories, onStoreCategoryRequestListener);
        } else {
            showStoreCategory();
        }
    }

    private OnRequestListener<List<Market>> onMarketAreaRequestListener = new OnRequestListener<List<Market>>() {
        @Override
        public List<Market> jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, new TypeToken<List<Market>>() {
            }.getType());
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {

            hideProgressDialog();
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {

            hideProgressDialog();
        }

        @Override
        public void onStart(Object tag) {
            showProgressDialog();
        }

        @Override
        public void onResponse(ResponseEntity<List<Market>> response, Object tag) {

            hideProgressDialog();
            List<Market> responseElement = response.getResponseElement();

            if (responseElement != null && responseElement.size() > 0) {
                openStoreMarketArea(responseElement);
            } else {
                toast("没有市场分区");
            }

        }
    };

    public void requestMarketArea(String id) {
//        store/market/areas

        if (id == null || "".equals(id)) {
//            toast("");
            return;
        }

        RequestEntityMapSupply RequestEntitySupply = new RequestEntityMapSupply();
        RequestEntitySupply.setCmd(com.epfresh.api.constant.AppSupplyRouterConstant.cmd_store_store_market_areas);

        RequestEntitySupply.putParameter("id", id);
        request(RequestEntitySupply, com.epfresh.api.constant.AppSupplyRouterConstant.cmd_store_store_market_areas, onMarketAreaRequestListener);
    }


}
